package com.ziyuan.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ziyuan.mapper.ArticleMapper;
import com.ziyuan.pojo.Article;
import com.ziyuan.pojo.PageBean;
import com.ziyuan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleService implements com.ziyuan.service.ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
//        获取tokenID
        Map<String, String> o = ThreadLocalUtil.get();
        Integer s = Integer.parseInt(o.get("id"));
//        补全实体类
        article.setCreateUser(s);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.inster(article);

    }

    @Override
    public void update(Article article) {
//        获取tokenID
        Map<String, String> o = ThreadLocalUtil.get();
        Integer s = Integer.parseInt(o.get("id"));
//        补全实体类
        article.setCreateUser(s);
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);

    }

    @Override
    public Article get(Integer id) {

//        补全实体类
        return articleMapper.Get(id);
    }

    @Override
    public void Delete(Integer id) {
        articleMapper.delete(id);

    }

    @Override
    public PageBean<Article> pageList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
//实例化PageBean
        PageBean<Article> pageBean = new PageBean<>();
//        启动PageHelper
        PageHelper.startPage(pageNum, pageSize);
//        获取用户id
        Map<String, String> o = ThreadLocalUtil.get();
        Integer s = (Integer.parseInt(o.get("id")));
//        传数据给mapper层，并修改返回格式
        List<Article> list =  articleMapper.Page(categoryId, state, s);
        PageInfo<Article> articlePageInfo = new PageInfo<>(list);
        pageBean.setItems(list);
        pageBean.setTotal(articlePageInfo.getTotal());


        return pageBean;

//        PageInfo<Article> articlePageInfo = new PageInfo<>(list);
//        Page<Article> list1 = (Page<Article>) list;
////        配置实体类PageBean
//        pageBean.setItems(list1);
//        pageBean.setTotal(list1.getTotal());
//        return pageBean;
    }

}
